﻿var calendar;
var currentCalendarMonth;
var currentCalendarYear;
var currentCalendarDate;

$(function () {
    currentCalendarDate = new Date();
    currentCalendarMonth = currentCalendarDate.getMonth();
    currentCalendarYear = currentCalendarDate.getFullYear();

    $.datepicker.regional['es'] = {
        closeText: 'Cerrar',
        prevText: '<Ant',
        nextText: 'Sig>',
        currentText: 'Hoy',
        monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
        monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
        dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
        dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mié', 'Juv', 'Vie', 'Sáb'],
        dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá'],
        weekHeader: 'Sm',
        dateFormat: 'dd/mm/yy',
        firstDay: 1,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ''
    };
    $.datepicker.setDefaults($.datepicker.regional['es']);

    //Index
    if ($('#hdnCalendar').val() == 1) {
        $('#pnlFilters').show();
        $('#pnlAppointmentsList').hide();
        InitAutocompleteFilter();
    }
    else {  //Calendar
        $('#pnlAppointmentsList').show();
        $('#pnlFilters').hide();

        var date = new Date();
        var mm = date.getMonth();
        var dd = date.getDate();
        var yyyy = date.getFullYear();
        GetAppointments(AddZero(dd) + '/' + AddZero((mm + 1)) + '/' + yyyy);

        //Carga los eventos por primera vez para el mes actual.
        GetEvents(currentCalendarMonth, currentCalendarYear);
    }

    $('#txtStartTime').timepicker({
        timeFormat: 'hh:mm tt',
        stepHour: 1,
        stepMinute: 10
    });

    $('#smallCalendar').datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'dd/mm/yy',
        onSelect: function (date) {

            var dd = parseInt(date.substring(0, 2));
            var mm = parseInt(date.substring(3, 5)) - 1;
            var yyyy = parseInt(date.substring(6, 10));
            var selectedDate = new Date(yyyy, mm, dd);
            currentCalendarDate = selectedDate;

            if ($('#hdnCalendar').val() == 1) {
                window.location = "/ODSYSUI/Appointment/SetSearchType?selectedDate=" + (AddZero(dd) + '/' + AddZero((mm + 1)) + '/' + yyyy);
            }

            if ($('#hdnCalendar').val() == 2) {   //Si se está en la pantalla del calendario
                GetAppointments(AddZero(dd) + '/' + AddZero((mm + 1)) + '/' + yyyy);    //Consulta las citas de ese día.
                //Si es un mes diferente obtiene todos los eventos para ese mes.
                if ((mm != currentCalendarMonth || yyyy != currentCalendarYear) && $('#hdnCalendar').val() == 2) {
                    $('#calendar').fullCalendar('removeEvents');
                    GetEvents(mm, yyyy);
                }

                $('#calendar').fullCalendar('gotoDate', selectedDate);
            }
        }
    });
});

function ConvertTicksToDate(pTicks) {
    try {
        var dateTimeObject;
        dateTimeObject = new Date((pTicks - 621355968000000000) / 10000);
        return dateTimeObject;
    }
    catch (Err) {
        return 'NAN';
    }
}

function GetDateFormatDMY(date) {
    
    var d = date.getDate();
    var m = date.getMonth() + 1;
    var y = date.getFullYear();
    var result = '' + (d <= 9 ? '0' + d : d).toString() + '/' + (m <= 9 ? '0' + m : m).toString() + '/' + y.toString();
    return result;
}

function GetAppointments(date) {
    $.ajax(
        {
            type: "POST",
            traditional: true,
            url: $('#urlGetAppointments').val(),
            secureuri: false,
            dataType: 'json',
            data:
                JSON.stringify({
                    currentDate: date
                }),
            contentType: 'application/json; charset=utf-8',
            enctype: 'multipart/form-data',
            success: function (data, status) {
                if (typeof (data) != 'undefined') {

                    $('#lstEventsLists li').remove();
                    $('#datDate').text(date);

                    if (data.length <= 0)
                        $('#pnlAppointmentsList').hide();
                    else {
                        $('#numAppointments').text(data.length);
                        var eventsList = new Array();

                        for (var i = 0; i < data.length; i++) {
                            var horaInicioCita = new Date(parseInt(data[i].startTime.substr(6)));
                            var strStartTime = [[FormatHours(startTime.getHours()), AddZero(startTime.getMinutes())].join(":"), startTime.getHours() >= 12 ? "pm" : "am"].join(" ");
                            var nombreCompleto = data[i].fullName;
                            var item = "<li onclick='GetAppointment(" + data[i].appointmentID + ", calendar)' style='cursor: pointer;'>" +
                                            "<a href='javascript:void(0)' class='float-left' style='height: 20px;'><img src='/ODSYSUI/Content/Images/icons/fugue/status.png' width='16' height='16'> " + data[i].description + "</a>" +
                                            "<ul class='tags float-right'>" +
                                                "<li class='tag-time' style='margin-left: 10px;'>" + strStartTime + "</li>" +
                                                "<li class='tag-user' style='margin-left: 10px;'>" + nombreCompleto + "</li>" +
                                            "</ul>" +
                                         "</li>";

                            $("#lstEventsLists").append(item);
                        }
                    }
                }
                else {
                    alert(data.msg);
                }
            },
            error: function (data, status, e) {
                alert(e);
            }
        });
}

function GetEvents(currentCalendarMonth, currentCalendarYear) {
    var date = new Date();
    var d = date.getDate();
    var m = date.getMonth();
    var y = date.getFullYear();

    $.ajax({
        type: "POST",
        traditional: true,
        url: $('#urlGetEvents').val(),
        secureuri: false,
        dataType: 'json',
        data:
                JSON.stringify({
                    selectedMonth: currentCalendarMonth,
                    selectedYear: currentCalendarYear
                }),
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        success: function (data, status) {
            var eventsList = new Array();
            for (var i = 0; i < data.length; i++) {
                eventsList[i] = {
                    id: data[i].appointmentID,
                    title: data[i].description,
                    start: new Date(parseInt(data[i].startTime.substr(6))),
                    end: new Date(parseInt(data[i].endTime.substr(6))),
                    allDay: false
                };
            }

            $('#calendar').fullCalendar('destroy');
            calendar = $('#calendar').fullCalendar({
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'agendaDay,agendaWeek,month'
                },
                selectable: true,
                selectHelper: true,
                select: function (start, end, allDay) {
                    if ((start - new Date(y, m, d)) >= 0)
                        openEventWindow(start, end, false, calendar, 0, 0, 0);
                    else
                        alert('Las citas solo se asignan a partir de la fecha actual.');
                },
                editable: true,
                eventClick: function (calEvent, jsEvent, view) {
                    GetAppointment(calEvent.id, calendar);
                },
                eventMouseover: function (event, jsEvent, view) {

                },
                eventMouseout: function (event, jsEvent, view) {

                },
                eventResize: function(event, dayDelta, minuteDelta, revertFunc) {
                    var originalEndDate = new Date(event.end.getTime());

                    if (minuteDelta < 0)  //Se adelantó la cita (minutos o horas)
                        originalEndDate.setMinutes(originalEndDate.getMinutes() + (minuteDelta * -1));
                    else if (minuteDelta > 0)  //Se atrasó la cita (minutos o horas)
                        originalEndDate.setMinutes(originalEndDate.getMinutes() - minuteDelta);
                    
                    if (dayDelta < 0)  //Se adelantó la cita (dias)
                        originalEndDate.setDate(originalEndDate.getDate() + (dayDelta * -1));
                    else if (dayDelta > 0)  //Se atrasó la cita (dias)
                        originalStartDate.setDate(originalStartDate.getDate() - dayDelta);

                    if ((event.start - new Date(y, m, d)) >= 0) {
                        if (confirm("¿Esta seguro que desea modificar el evento?")) {                            
                            UpdateAppointment(event.start, event.end, event.id);
                        }
                        else {                            
                            event.end = originalEndDate;
                            $('#calendar').fullCalendar('updateEvent', event)
                        }
                    }
                    else {
                        alert('Las citas solo se asignan a partir de la fecha actual.');
                        event.end = originalEndDate;
                        $('#calendar').fullCalendar('updateEvent', event)
                    }
                },
                eventDrop: function (event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view) {
                    var originalStartDate = new Date(event.start.getTime());
                    var originalEndDate = new Date(event.end.getTime());

                    if (minuteDelta < 0) {  //Se adelantó la cita (minutos o horas)
                        originalStartDate.setMinutes(originalStartDate.getMinutes() + (minuteDelta * -1));
                        originalEndDate.setMinutes(originalEndDate.getMinutes() + (minuteDelta * -1));
                    }
                    else if (minuteDelta > 0) {  //Se atrasó la cita (minutos o horas)
                        originalStartDate.setMinutes(originalStartDate.getMinutes() - minuteDelta);
                        originalEndDate.setMinutes(originalEndDate.getMinutes() - minuteDelta);
                    }

                    if (dayDelta < 0) { //Se adelantó la cita (dias)
                        originalStartDate.setDate(originalStartDate.getDate() + (dayDelta * -1));
                        originalEndDate.setDate(originalEndDate.getDate() + (dayDelta * -1));
                    }
                    else if (dayDelta > 0) {  //Se atrasó la cita (dias)
                        originalStartDate.setDate(originalStartDate.getDate() - dayDelta);
                        originalEndDate.setDate(originalEndDate.getDate() - dayDelta);
                    }

                    if ((event.start - new Date(y, m, d)) >= 0) {
                        if (confirm("¿Esta seguro que desea modificar el evento?")) {                            
                            UpdateAppointment(event.start, event.end, event.id);
                        }
                        else {                            
                            event.start = originalStartDate;
                            event.end = originalEndDate;
                            $('#calendar').fullCalendar('updateEvent', event)
                        }
                    }
                    else {
                        alert('Las citas solo se asignan a partir de la fecha actual.');
                        event.start = originalStartDate;
                        event.end = originalEndDate;
                        $('#calendar').fullCalendar('updateEvent', event)
                    }
                },
                events: eventsList
            });
            calendar.fullCalendar('changeView', 'agendaDay');

            $('.fc-button-prev').click(function () {
                currentCalendarDate.setDate(currentCalendarDate.getDate() - 1);
                var mm = currentCalendarDate.getMonth();
                var dd = currentCalendarDate.getDate();
                var yyyy = currentCalendarDate.getFullYear();
                var strDate = AddZero(dd) + '/' + AddZero((mm + 1)) + '/' + yyyy;
                $("#smallCalendar").datepicker("setDate", strDate);
            });

            $('.fc-button-next').click(function () {
                currentCalendarDate.setDate(currentCalendarDate.getDate() + 1);
                var mm = currentCalendarDate.getMonth();
                var dd = currentCalendarDate.getDate();
                var yyyy = currentCalendarDate.getFullYear();
                var strDate = AddZero(dd) + '/' + AddZero((mm + 1)) + '/' + yyyy;

                if ((currentCalendarDate.getMonth() != currentCalendarMonth || currentCalendarDate.getFullYear() != currentCalendarYear) && $('#hdnCalendar').val() == 2) {
                    $('#calendar').fullCalendar('removeEvents');
                    GetEvents(currentCalendarDate.getMonth(), currentCalendarDate.getFullYear());
                }

                $("#smallCalendar").datepicker("setDate", strDate);
            });

            $('.fc-button-inner').click(function () {
                if ((this.innerHTML.indexOf('Hoy')) != -1 && (this.offsetParent.className.indexOf('disabled') == -1)) {
                    var today = new Date();
                    var strDate = AddZero(today.getDate()) + '/' + AddZero((today.getMonth() + 1)) + '/' + today.getFullYear();

                    if ((currentCalendarDate.getMonth() != currentCalendarMonth || currentCalendarDate.getFullYear() != currentCalendarYear) && $('#hdnCalendar').val() == 2) {
                        $('#calendar').fullCalendar('removeEvents');
                        GetEvents(currentCalendarDate.getMonth(), currentCalendarDate.getFullYear());
                    }

                    $("#smallCalendar").datepicker("setDate", strDate);
                }
            });
        },
        error: function (data, status, e) {
            alert(e);
        }
    });
}

function openEventWindow(start, end, allDay, calendar, id, idMedic, idCubicle) {
    var selectedDate = start;//new Date(currentYear, currentMonth, date);
    
    var popUp = $.modal({
        content:    "<input type='hidden' id='customerID' name='customerID' />" +
                    "<div class='block-content form'><div class='columns'>" +
                        "" +
						    "<form id='frmPopUp' name='frmPopUp' method='post'>" +
							    "<fieldset>" +
									"<div class='columns'>" +
										"<label for='txtEvent'>Evento</label>" +
                                        "<span class='relative'>" +
										    "<input type='text' name='txtEvent' id='txtEvent' value='' class='full-width'>" +
                                        "</span>" +
								    "</div>" +
								    "<div class='columns'>" +
									    "<p class='colx2-left'>" +
										    "<label for='txtStartHour'>Hora Inicio</label>" +
											"<span class='relative'>" +
											    "<input type='text' name='txtStartHour' id='txtStartHour' value='' class='full-width'>" +
											"</span>" +
									    "</p>" +
									    "<p class='colx2-right'>" +
										    "<label for='txtEndHour'>Hora Final</label>" +
                                            "<span class='relative'>" +
										        "<input type='text' name='txtEndHour' id='txtEndHour' value='' class='full-width'>" +
                                            "</span>" +
									    "</p>" +
								    "</div>" +

                                    "<div class='columns' style='margin-bottom: 0px;'>" +
									    "<p class='colx2-left'>" +
										    "<label for='txtStartHour'>Tipo de búsqueda</label>" +
											"<span class='relative'>" +
											    "<input type='radio' name='rdbSearchType' id='rdbName' value='name' checked='checked'> Por Nombre" +
											"</span>" +
									    "</p>" +
									    "<p class='colx2-right' style='margin-top: 15px;'>" +
										    "<label for='txtEndHour'></label>" +
                                            "<span class='relative'>" +
										        "<input type='radio' name='rdbSearchType' id='rdbID' value='id'> Por Identificación" +
                                            "</span>" +
									    "</p>" +
								    "</div>" +

                                    "<div class='columns'>" +
										"<span class='relative'>" +
                                            "<input type='text' name='txtCustomer' id='txtCustomer' maxlength='40' class='full-width' style='background-image:url(/ODSYSUI/Content/Images/Forms/Search.gif); background-position:left; background-repeat:no-repeat; background-position: right center;'>" +
                                        "</span>" +
								    "</div>" +
                                    "<div class='columns'>" +
										"<label for='cmbMedic'>Médico</label>" +
                                        "<span class='relative'>" +
										    "<select name='cmbMedic' id='cmbMedic' class='full-width '>" +
                                                "<option value=''>Seleccione</option>" +
										    "</select>" +
                                        "</span>" +
								    "</div>" +
									"<div class='columns'>" +
										"<label for='cmbCubicle'>Consultorio</label>" +
										"<span class='relative'>" +
                                            "<select name='cmbCubicle' id='cmbCubicle' class='full-width '>" +
                                                "<option value=''>Seleccione</option>" +
										    "</select>" +
                                        "</span>" +
								    "</div>" +

                                    "<div class='columns'>" +
										"<label for='chkEmail'>Enviar correo electrónico para la confirmación </label>" +
                                        "<input type='checkbox' name='chkEmail' id='chkEmail' value='' class='mini-switch' checked='checked'>" +
								    "</div>" +

							    "</fieldset>" +
						    "</form>" +
				        "</div></div>",
        title: 'Evento para el día ' + GetDateFormatDMY(selectedDate),
        maxWidth: 500,
        buttons: {
            'Limpiar': function (win) { /*ClearPopUp();*/ SaveAppointment(start, end, allDay, popUp, calendar, id); },
            'Guardar': function (win) {
                if (isValidPopUp()) {
                    //if (SaveAppointment(start, end)) {    //popUp
                    //    calendar.fullCalendar('renderEvent',
                    //        {
                    //            title: $("#txtEvent").val(),
                    //            start: start,
                    //            end: end,
                    //            allDay: allDay
                    //        },
                    //        true // make the event "stick"
                    //    );
                    //    popup.closeModal();
                    //}
                    SaveAppointment(start, end, allDay, popUp, calendar, id);
                }
            },
            'Eliminar': function (win) {
                if (confirm("¿Esta seguro que desea eliminar el evento?")) {
                    DeleteAppointment(id);
                    $('#calendar').fullCalendar('removeEvents', id);
                    win.closeModal();
                }
            },
            'Cerrar': function (win) { win.closeModal(); }
        }
    });

    if (id <= 0) {
        $(':button:contains("Eliminar")').hide();
    }

    InitPopUp(start, end, idMedic, idCubicle);
}

function GetMedics(idMedic, idCubicle) {
    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $('#urlGetMedics').val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        success: function (data, status) {
            if (typeof (data) != 'undefined') {
                if (data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        var itemText = data[i].name + " " + data[i].firstName + " " + data[i].lastName;
                        var itemValue = data[i].personID;
                        var option = $('<option />');
                        option.attr('value', itemValue).text(itemText);

                        if (idMedic > 0 && idMedic == itemValue)
                            option.attr('selected', 'selected')

                        $('#cmbMedic').append(option);
                    }
                }
            }
            GetCubicles(idCubicle);
        },
        error: function (data, status, e) {
            alert(e);
        }
    });
}

function GetCubicles(idCubicle) {
    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $('#urlGetConsultingRooms').val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        success: function (data, status) {
            if (typeof (data) != 'undefined') {
                if (data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        var itemText = data[i].name;
                        var itemValue = data[i].consultingRoomID;
                        var option = $('<option />');
                        option.attr('value', itemValue).text(itemText);

                        if (idCubicle > 0 && idCubicle == itemValue)
                            option.attr('selected', 'selected')

                        $('#cmbCubicle').append(option);
                    }
                }
            }
            InitAutocomplete();
        },
        error: function (data, status, e) {
            alert(e);
        }
    });
}

function SaveAppointment(start, end, allDay, popUp, calendar, id) {
    var sh = parseInt($('#txtStartHour').val().substring(0, 2));
    var sm = $('#txtStartHour').val().substring(3, 5);
    var sAmPm = $('#txtStartHour').val().substring(6, 8);

    if (sAmPm != 'am' && sh != 12)
        sh = sh + 12;

    var eh = parseInt($('#txtEndHour').val().substring(0, 2));
    var em = $('#txtEndHour').val().substring(3, 5);
    var eAmPm = $('#txtEndHour').val().substring(6, 8);

    if (eAmPm != 'am' && eh != 12)
        eh = eh + 12;

    var startTime = new Date(start.getFullYear(), start.getMonth(), start.getDate(), sh, sm);
    var endTime = new Date(end.getFullYear(), end.getMonth(), end.getDate(), eh, em);

    if (id <= 0) {
        $.ajax(
        {
            type: "POST",
            traditional: true,
            url: $("#urlSaveAppointment").val(),
            secureuri: false,
            dataType: 'json',
            data:
                JSON.stringify({
                    personID: $('#customerID').val(),
                    medicID: $('#cmbMedic').val(),
                    date: start,
                    startTime: startTime,
                    endTime: endTime,
                    description: $('#txtEvent').val(),
                    consultingRoomID: ($('#cmbCubicle').val() != '' || $('#cmbCubicle').val() != 'undefined') ? $('#cmbCubicle').val() : '',
                    sendEmail: $('#chkEmail').is(':checked')
                }),
            contentType: 'application/json; charset=utf-8',
            enctype: 'multipart/form-data',
            success: function (data, status) {                
                if (typeof (data) != 'undefined') {
                    if (data.success) {
                        calendar.fullCalendar('renderEvent',
                            {
                                id: data.eventID,
                                title: $("#txtEvent").val(),
                                start: startTime,
                                end: endTime,
                                allDay: allDay
                            },
                            true // make the event "stick"
                        );

                        var mm = start.getMonth();
                        var dd = start.getDate();
                        var yyyy = start.getFullYear();
                        GetAppointments(AddZero(dd) + '/' + AddZero((mm + 1)) + '/' + yyyy);

                        if (popUp != 'undefined')
                            popUp.closeModal();
                    }
                    else {
                        alert(data.msg);
                    }
                }
            },
            error: function (data, status, e) {                
                alert(e);
            }
        });
    }
    else {        
        $.ajax(
        {
            type: "POST",
            traditional: true,
            url: $("#urlUpdateAppointment").val(),
            secureuri: false,
            dataType: 'json',
            data:
                JSON.stringify({
                    appointmentID: id,
                    personID: $('#customerID').val(),
                    medicID: $('#cmbMedic').val(),
                    date: start,
                    startTime: startTime,
                    endTime: endTime,
                    description: $('#txtEvent').val(),
                    consultingRoomID: ($('#cmbCubicle').val() != '' || $('#cmbCubicle').val() != 'undefined') ? $('#cmbCubicle').val() : '',
                    sendEmail: $('#chkEmail').is(':checked')
                }),
            contentType: 'application/json; charset=utf-8',
            enctype: 'multipart/form-data',
            success: function (data, status) {
                if (typeof (data) != 'undefined') {
                    if (data.success) {
                        calendar.fullCalendar('removeEvents', id);  //Se elimina el evento del Calendario
                        calendar.fullCalendar('renderEvent',        //Se agrega el evento actualizado al Calendario
                            {
                                id: data.eventID,
                                title: $("#txtEvent").val(),
                                start: startTime,
                                end: endTime,
                                allDay: allDay
                            },
                            true // make the event "stick"
                        );

                        var mm = start.getMonth();
                        var dd = start.getDate();
                        var yyyy = start.getFullYear();
                        GetAppointments(AddZero(dd) + '/' + AddZero((mm + 1)) + '/' + yyyy);

                        if (popUp != 'undefined')
                            popUp.closeModal();
                    }
                    else {
                        alert(data.msg);
                    }
                }
            },
            error: function (data, status, e) {
                alert(e);
            }
        });
    }
}

function UpdateAppointment(start, end, id) {
    
    if (id > 0) {
        $.ajax(
        {
            type: "POST",
            traditional: true,
            url: $("#urlUpdateAppointment").val(),
            secureuri: false,
            dataType: 'json',
            data:
                JSON.stringify({                    
                    appointmentID: id,
                    date: start,
                    startTime: start,
                    endTime: end,
                    sendEmail: true
                }),
            contentType: 'application/json; charset=utf-8',
            enctype: 'multipart/form-data',
            success: function (data, status) {
                if (typeof (data) != 'undefined') {
                    if (data.success) {
                        var mm = start.getMonth();
                        var dd = start.getDate();
                        var yyyy = start.getFullYear();
                        GetAppointments(AddZero(dd) + '/' + AddZero((mm + 1)) + '/' + yyyy);
                    }
                    else {
                        alert(data.msg);
                    }
                }
            },
            error: function (data, status, e) {
                alert(e);
            }
        });
    }
}

function GetAppointment(id, calendar) {
    if (id > 0) {
        $.ajax(
            {
                type: "POST",
                traditional: true,
                url: $("#urlGetAppointment").val(),
                secureuri: false,
                dataType: 'json',
                data:
                    JSON.stringify({
                        id: id
                    }),
                contentType: 'application/json; charset=utf-8',
                enctype: 'multipart/form-data',
                success: function (data, status) {
                    if (typeof (data) != 'undefined') {
                        if (data.success) {
                            var horaInicioCita = new Date(parseInt(data.horaInicioCita.substr(6)));
                            var horaFinCita = new Date(parseInt(data.horaFinCita.substr(6)));

                            openEventWindow(horaInicioCita, horaFinCita, false, calendar, id, data.idMedico, data.idConsultorio);

                            $('#customerID').val(data.idPaciente);
                            $('#txtEvent').val(data.motivo);
                            $('#txtCustomer').val(data.paciente);
                        }
                        else {
                            alert(data.msg);
                        }
                    }
                },
                error: function (data, status, e) {
                    alert(e);
                }
            });
    }
}

function DeleteAppointment(id) {
    if (id > 0) {
        $.ajax(
            {
                type: "POST",
                traditional: true,
                url: $('#urlDeleteAppointment').val(),
                secureuri: false,
                dataType: 'json',
                data:
                    JSON.stringify({
                        id: id,
                        sendEmail: $('#chkEmail').is(':checked')
                    }),
                contentType: 'application/json; charset=utf-8',
                enctype: 'multipart/form-data',
                success: function (data, status) {
                    if (typeof (data) != 'undefined') {
                        alert(data.msg);

                        var deletedDate = new Date(parseInt(data.appointmentDate.substr(6)));
                        var mm = deletedDate.getMonth();
                        var dd = deletedDate.getDate();
                        var yyyy = deletedDate.getFullYear();
                        GetAppointments(AddZero(dd) + '/' + AddZero((mm + 1)) + '/' + yyyy);
                    }
                },
                error: function (data, status, e) {
                    alert(e);
                }
            });
    }
}

function InitPopUp(start, end, idMedic, idCubicle) {
    var validatorCalendar = $("#frmPopUp").bind("invalid-form.validate", function () {
        //$("#lblPopUpErrorMsg").show();
    }).validate({
        debug: true,
        rules: {
            txtEvent: {
                required: true,
                minlength: 5
            },
            txtDescription: {
                required: true,
                minlength: 5
            },
            txtStartHour: {
                required: true,
                minlength: 7
            },
            txtEndHour: {
                required: true,
                minlength: 7
            },
            txtCustomer: {
                required: true,
                minlength: 5
            },
            cmbMedic: 'required'
        },
        messages: {
            txtEvent: "Ingrese el título",
            txtDescription: "Ingrese la descripción",
            txtStartHour: "Ingrese hora de inicio",
            txtEndHour: "Ingrese hora final",
            txtCustomer: "Ingrese el paciente",
            cmbMedic: "Seleccione el médico",
        }
    });

    ClearPopUp();
    //$('#txtStartHour').timeEntry({ timeSteps: [1, 30, 0] });
    //$('#txtEndHour').timeEntry({ timeSteps: [1, 30, 0] });

    $('#txtStartHour').timepicker({
        timeFormat: 'hh:mm tt',
        stepHour: 1,
        stepMinute: 10
    });

    $('#txtEndHour').timepicker({
        timeFormat: 'hh:mm tt',
        stepHour: 1,
        stepMinute: 10
    });

    var strStartTime = [[FormatHours(start.getHours()), AddZero(start.getMinutes())].join(":"), start.getHours() >= 12 ? "pm" : "am"].join(" ");
    var strEndTime = [[FormatHours(end.getHours()), AddZero(end.getMinutes())].join(":"), end.getHours() >= 12 ? "pm" : "am"].join(" ");

    $('#txtStartHour').val(strStartTime);
    $('#txtEndHour').val(strEndTime);

    GetMedics(idMedic, idCubicle);
}

function InitAutocomplete() {
    $("#txtCustomer").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST",
                url: $('#urlGetPatients').val(),
                dataType: "json",
                data: {
                    searchString: request.term,
                    IsByName: $('#rdbName').is(':checked'),
                    maxRows: 12
                },
                parse: function (data) {
                    var rows = new Array();
                    for (var i = 0; i < data.length; i++) {
                        rows[i] = { data: data[i], value: data[i].name, result: data[i].name };
                    }
                    return rows;
                },
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.name + " " + item.firstName + " " + item.lastName + ". ID: " + item.identification,
                            ID: item.personID,
                            Name: item.name,
                            FirstName: item.firstName,
                            LastName: item.lastName,
                            Identification: item.identification,
                            DefaultPhone: item.defaultPhone
                        }
                    }));
                },
                error: function (data, status, e) {
                    alert(e);
                }
            });
        },
        minLength: 0,
        select: function (event, ui) {
            $("#customerID").val(ui.item.ID);
        }
    });

    $("#txtCustomer").keyup(function () {
        if (!this.value) {
            $('#customerID').val();
        }
    });
}

function InitAutocompleteFilter() {
    $("#txtCustomerFilter").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST",
                url: $('#urlGetPatients').val(),
                dataType: "json",
                data: {
                    searchString: request.term,
                    IsByName: $('#rdbNameFilter').is(':checked'),
                    maxRows: 12
                },
                parse: function (data) {
                    var rows = new Array();
                    for (var i = 0; i < data.length; i++) {
                        rows[i] = { data: data[i], value: data[i].name, result: data[i].name };
                    }
                    return rows;
                },
                success: function (data) {                    
                    response($.map(data, function (item) {
                        return {
                            label: item.name + " " + item.firstName + " " + item.lastName + ". ID: " + item.identification,
                            ID: item.personID,
                            Name: item.name,
                            FirstName: item.firstName,
                            LastName: item.lastName,
                            Identification: item.identification,
                            DefaultPhone: item.defaultPhone
                        }
                    }));
                },
                error: function (data, status, e) {                    
                    alert(e);
                }
            });
        },
        minLength: 0,
        select: function (event, ui) {
            $("#customerFilterID").val(ui.item.ID);
        }
    });

    $("#txtCustomerFilter").keyup(function () {
        if (!this.value) {
            $('#customerFilterID').val();
        }
    });
}

function SearchPatients() {
    if ($('#customerFilterID').val() != '' || $('#ddlMedic').val() != '' || $('#ddlStatus').val() != '' || $('#ddlTimeSearch').val() != '') {
        window.location = $("#urlSearchAppointments").val() + "?pacienteID=" + $('#customerFilterID').val() + "&medicoID=" + $('#ddlMedic').val() + "&estadoCita=" + $('#ddlStatus').val() + "&periodoID=" + $('#ddlTimeSearch').val();
    }
}

function GetContactImage(type) {
    var value = "exclamation-diamond.png";
    switch (type) {
        case 1: value = "Email.png"; break;
        case 2: value = "Mobile.png"; break;
        case 3: value = "Phone.png"; break;
    }
    return value;
}

function AddZero(num) {
    return (num >= 0 && num < 10) ? "0" + num : num + "";
}

function FormatHours(num) {
    var result;
    if (num >= 0 && num <= 12) {
        if (num == 0)
            num = 12;
        result = AddZero(num);
    }
    if (num >= 13 && num <= 23) {
        num = num - 12;
        result = AddZero(num);
    }
    return result;
}

function IsValidTime() {    
    var start_time = $("#txtStartHour").val();
    var end_time = $("#txtEndHour").val();

    if (start_time == end_time)
        return false;

    //convert both time into timestamp
    var stt = new Date("November 13, 2013 " + start_time);
    stt = stt.getTime();

    var endt = new Date("November 13, 2013 " + end_time);
    endt = endt.getTime();

    if (stt > endt)
        return false;
    else
        return true;
}

function isValidPopUp() {
    var isValid = false;
    if ($("#frmPopUp").valid()) {
        $("#lblPopUpErrorMsg").hide();
        isValid = true;
    }

    if (isValid) {
        isValid = IsValidTime();
        if (!isValid) {
            $('#frmPopUpErrorMessage').text('La hora de inicio no puede ser mayor o igual a la hora final');
            $('#lblPopUpErrorMsg').show();
            $("#txtStartHour").addClass("error");
            $("#txtEndHour").addClass("error");
        }
        else {
            $('#frmPopUpErrorMessage').text('Debe llenar todos los campos obligatorios');
            $('#lblPopUpErrorMsg').hide();
            $("#txtStartHour").removeClass("error");
            $("#txtEndHour").removeClass("error");
        }
    }
    return isValid;
}

function ClearPopUp() {
    //$('#lblPopUpErrorMsg').hide();

    //var cmbCustomer = $('#cmbCustomer');
    var cmbMedic = $('#cmbMedic');
    var cmbCubicle = $('#cmbCubicle');

    //cmbCustomer[0].selectedIndex = 0;
    cmbMedic[0].selectedIndex = 0;
    cmbCubicle[0].selectedIndex = 0;

    $('#txtEvent').val('');
    $('#txtDescription').val('');
    $('#txtCustomer').val('');
    $('#txtStartHour').val('');
    $('#txtEndHour').val('');

    $("#txtEvent").removeClass("error");
    $("#txtDescription").removeClass("error");
    $("#txtCustomer").removeClass("error");
    $("#txtStartHour").removeClass("error");
    $("#txtEndHour").removeClass("error");
    $("#cmbMedic").removeClass("error");

    $('#chkEmail').attr('checked', false);

    $(".error").remove();
}